<template>
  <div class="menu-index">
    <!-- 轮播图 -->
    <!--  -->
    <van-swipe  :autoplay="2000" class="my-swipe" indicator-color="white">
      <van-swipe-item v-for="banner in bannerUrl" :key="banner.id" >
        <img :src="'http://img.zuiyu1818.cn' + banner.imgUrl"/>
      </van-swipe-item>
    </van-swipe>
    <!-- 左侧内容 -->
    <van-tree-select :items="leftlist" height="72vh" :main-active-index.sync="active" selected-icon="" @click-nav="changeHandler"  class="concent">
      <!-- 右侧内容 -->
      <template #content>
        <!-- 循环渲染右侧列表内容 -->
        <!-- 热门商品 -->
        <van-list
          v-for="(items, i) in Object.values(lists)"
          :key='i'
        >
        <div  :id="'product' + i">
              <van-divider>{{items.text}}</van-divider>
              <van-cell v-for="(detail, ii) in items.data" :key="ii" :id="detail.id">
                  <template #title>
                  <span class="title">{{detail.shop_name}}</span>
                  <div class="ftitle">
                    {{detail.shop_desc}}
                  </div>
                  <span class="price">{{detail.shop_price}}</span>
                  </template>
                  <template #icon >
                    <van-image  lazy-load :src="'http://img.zuiyu1818.cn' + detail.shop_imgUrl"  style="width:60px;height:60px;"/>
                  </template>
                  <template #extra>
                    <div class="yuan" @click="tellUs(detail.id)">+</div>
                  </template>
              </van-cell>
        </div>
        </van-list>
      </template>
    </van-tree-select>
      <van-popup v-model="isShow" class="bigkuang" round lazy-render closeable @close="closes" safe-area-inset-bottom v-if="itemlist[0]">
        <div class="kuang">
          <van-image width="100%" :src="'http://img.zuiyu1818.cn' + itemlist[0].shop_imgUrl"></van-image>
          <van-field v-if="sort.model" name="radio" label="规格" label-width="2em">
              <template #input>
                <van-radio-group v-model="radio"  direction="horizontal">
                  <van-button :class="ind == index ? 'intro':''" v-for="(cup, ind) in cups" :key="ind" type="default" size="mini" @click="selectCup(cup.id,ind)" style="width:50px">{{cup.title}}</van-button>
                </van-radio-group>
              </template>
          </van-field>
          <van-field v-if="sort.model" name="radio" label="温度" label-width="2em">
              <template #input>
                <van-radio-group v-model="radio"  direction="horizontal">
                  <van-button :class="indss == indexs ? 'intro':''" v-for="(temperatur,indss) in temperature" :key="indss" type="default" size="mini" @click="selectTemperature(temperatur.id,indss)" style="width:50px">{{temperatur.title}}</van-button>
                </van-radio-group>
              </template>
          </van-field>
          <van-field v-if="sort.model" name="radio" label="糖度" label-width="2em">
              <template #input>
                <van-radio-group v-model="radio" direction="horizontal">
                  <van-button :class="inds == indexss ? 'intro' : ''" v-for="(sweetens,inds) in sweetness" :key="inds" type="default" @click="selectSweetness(sweetens.id,inds)" size="mini" style="width:50px">{{sweetens.title}}</van-button>
                </van-radio-group>
              </template>
          </van-field>
          <div class="box">
            <p class="Choose_price">{{itemlist[0].shop_price}}</p>
            <div class="boxside">
              <span v-if=" index == null || indexs == null || indexss == null">请选择商品规格！</span>
              <span class="cup" v-if="sort.model || (index !== null || indexs !== null || indexss !== null)">{{title1}}</span><span v-if="sort.model || (index !== null || indexs !== null || indexss !== null)" class="temperature">{{title3}}</span><span v-if="sort.model || (index !== null || indexs !== null || indexss !== null)" class="Sweetness">{{title2}}</span>
              <van-stepper v-model="value" theme="round" integer button-size="22" style="color:#7AA7D4;" class="Stepper"/>
            </div>
            <van-divider />
            <div class="AddCart">
                <van-button icon="cart-o" type="info" size="small" hairline @click="addItemCart" >加入购物车</van-button>
            </div>

          </div>
        </div>
      </van-popup>
  </div>

</template>

<script>
import Vue from 'vue'
import { Swipe, SwipeItem, Lazyload, TreeSelect, Image as VanImage, List, Cell, Divider, Popup, Form, RadioGroup, Radio, Field, Button, Stepper, Toast } from 'vant'
import { getBannerUrl } from '@/API/banner'
import { getLists } from '@/API/lists'
import { sendItem } from '@/API/addCart'

// import axios from 'axios'

Vue.use(Lazyload)
Vue.use(Swipe)
Vue.use(SwipeItem)
Vue.use(TreeSelect)
Vue.use(VanImage)
Vue.use(List)
Vue.use(Cell)
Vue.use(Divider)
Vue.use(Popup)
Vue.use(Form)
Vue.use(Radio)
Vue.use(RadioGroup)
Vue.use(Field)
Vue.use(Button)
Vue.use(Stepper)
Vue.use(Toast)
export default {
  name: 'menu-index',

  created () {
    getBannerUrl().then(res => {
      if (res.meta.code === 200) {
        this.bannerUrl = res.body
        console.log('ss', this.bannerUrl)
      }
    }).catch(res => {
      console.log(res.meta)
    })
    getLists().then(res => {
      this.res = res

      this.lists = res.body
      // console.log(this.lists)

      // console.log(Object.values(this.lists)[0])
      // 过滤出热门商品
      const { beverages, coffee, food } = res.body
      this.HotLists = beverages.data.concat(coffee.data, food.data).filter(item => {
        return item.shop_popular !== false
      })
      console.log('人气TOP', this.HotLists)

      // 创建HOT列表
      var Hot = { id: Math.floor(Math.random() * 10000), text: '人气TOP', data: this.HotLists, model: Object.values(this.lists)[0].model }
      var ls = { popular: Hot }
      // 合并所有对象
      this.lists = Object.assign(ls, this.lists)
      console.log(this.lists)
      // console.log(res.body)
      // 获取左侧一级标题
      const str = []

      for (let i = 0; i < Object.keys(this.lists).length; i++) {
        str.push({ text: this.lists[Object.keys(this.lists)[i]].text })
      }
      this.leftlist = str
    })
  },
  data () {
    return {
      index: null,
      indexs: null,
      indexss: null,
      leftlist: [],
      flag: false,
      isShow: false,
      radio: '1',
      value: 1,
      active: 0,
      lists: [],
      res: [],
      HotLists: [],
      bannerUrl: [],
      itemlist: [],
      cups: [],
      sweetness: [],
      temperature: [],
      title1: '',
      title2: '',
      title3: '',
      id1: null,
      id2: null,
      id3: null,
      totlynum: 0
    }
  },
  mounted () {
    this.$nextTick(() => {
      document.querySelector('.van-tree-select__content').addEventListener('scroll', (e) => {
        this.flag = true
        this.ChangeActive(e)
      })
    })
  },
  methods: {
    closes () {
      this.index = null
      this.indexs = null
      this.indexss = null
      this.id1 = null
      this.id2 = null
      this.id3 = null
      this.title1 = ''
      this.title2 = ''
      this.title3 = ''
      this.value = 1
    },
    tellUs (id) {
      this.isShow = !this.isShow
      console.log('当前商品ID：', id)
      const { beverages, coffee, food } = this.res.body
      this.itemlist = beverages.data.concat(coffee.data, food.data).filter(item => {
        return item.id === id
      })
      // console.log(this.itemlist[0])
      // console.log(this.itemlist[0].shop_cate)

      this.sort = this.res.body[this.itemlist[0].shop_cate]
      // console.log(this.sort)
      if (this.sort.model) {
        this.cups = this.sort.model.cup
        // console.log(this.cups)
        this.sweetness = this.sort.model.sweetness
        // console.log(this.sweetness)
        this.temperature = this.sort.model.temperature
        // console.log(this.temperature)
      } else {
        console.log('没有model')
      }
    },
    addItemCart () {
      if (this.sort.model) {
        if (this.index === null || this.indexs === null || this.indexss === null) {
          console.log(this.sort.model)
          Toast.fail('加入购物车失败!请选择规格！')
        } else {
          var data = {
            shop_id: this.itemlist[0].id,
            cup: this.id1,
            temperature: this.id2,
            sweetness: this.id3,
            amount: this.value,
            shop_name: this.itemlist[0].shop_cate
          }
          sendItem(data).then(res => {
            console.log(res)
            Toast.success('添加商品到购物车成功！')
            this.totlynum = res.body.total.numTotal
            console.log(this.totlynum)
            this.$store.commit('updataNum', this.totlynum)
          })
        }
      } else {
        var datas = {
          shop_id: this.itemlist[0].id,
          cup: null,
          temperature: null,
          sweetness: null,
          amount: this.value,
          shop_name: this.itemlist[0].shop_cate
        }
        sendItem(datas).then(res => {
          console.log(res)
          Toast.success('添加商品到购物车成功！')
          this.totlynum = res.body.total.numTotal
          console.log(this.totlynum)
          this.$store.commit('updataNum', this.totlynum)
        })
      }
    },
    selectCup (id, idx) {
      this.title1 = this.cups[idx].title
      this.index = idx
      this.id1 = id
    },
    selectSweetness (id, idxs) {
      this.title2 = this.sweetness[idxs].title
      this.indexss = idxs
      this.id3 = id
    },
    selectTemperature (id, idxss) {
      this.title3 = this.temperature[idxss].title
      this.indexs = idxss
      this.id2 = id
    },
    changeHandler (index) {
      // this.active = index
      const len = Object.values(this.lists).length
      const heightArr = []
      for (let i = 0; i < len; i++) {
        heightArr.push(this.$el.querySelector('#product' + (i)).offsetTop)
      }

      this.$el.querySelector('.van-tree-select__content').scrollTop = heightArr[index]

      this.flag = false
    },
    ChangeActive (e) {
      // if (!this.flag) {
      //   return
      // }
      // const len = Object.values(this.details).length
      // const heightArr = []
      // for (let i = 0; i < len; i++) {
      //   heightArr.push(this.$el.querySelector('#product' + (i)).offsetTop)
      // }
      // console.log(e.target.scrollTop, heightArr)
      // heightArr.some((item, index) => {
      //   if (e.target.scrollTop < item) {
      //     this.active = index - 1
      //   }
      //   return e.target.scrollTop < item
      // })
      // console.log(this.active)
    }
  }
}
</script>

<style lang="scss" scoped>
.menu-index{
  padding-bottom: 50px;

  .my-swipe .van-swipe-item{
    height:100%;
    width:100%;
    img{
      width:100%;
    }
  }
  .concent{
    height:100%;
  }
  .title{
    font-size: 12px;
    color:#666;
    line-height:12px;
        overflow: hidden;
    text-overflow:ellipsis;
    white-space: nowrap;
    width: 160px;
    display: block;
    padding-left:5px;
    text-align: left;
  }
  .ftitle{
    font-size: 12px;
    overflow: hidden;
    text-overflow:ellipsis;
    white-space: nowrap;
    width:145px;
    color:#999;
    padding-left:5px;
  }
  .yuan{
      width: 20px;
      height:20px;
      border: 1px solid #ccc;
      border-radius: 50%;
      display: block;
      text-align: center;
      line-height:20px;
      color:#fff;
      background-color: #7AA7D4;
      font-size:22px;
      position: absolute;
      bottom:9px;
      right:20px;
  }
  span.price{
      font-size: 12px;
      color:#f40;
      padding-left:5px;
      &::before{
        content: '￥';
        color:#f40;
        // text-align: none;
    }
  }
  .bigkuang{
    // border-radius: 20px;
    .kuang{
    width:76vw;
    height:140vw;
    padding-bottom: 30px;
        .box{
          // display: flex;
          // flex-direction: column;
          font-size: 14px;
          // justify-content: center;
          // align-items: center;
          .Choose_price{
              font-size: 14px;
              margin:10px 0 10px 10px;

                &::before{
                  content: '￥';
                  color:#000;
              }
          }
          .boxside{
            margin: 10px 0 10px 10px;

          }
          .Stepper{
            float: right;
            margin-right:15px;
            // margin-top:15px;
          }
          .cup{
            text-align: left;
          }
        }
    }
    .AddCart{
      text-align: center;

    }

  }
  .van-cell__title{
    width:3em!important;
  }
  .van-field__label{
    width:3em!important;
  }
}
.intro{
  color:#fff;
  background-color: #7AA7D4;
}
</style>
